﻿using System.Collections.ObjectModel;
using SQLite;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Wimm.Common.Entities;
using Wimm.Common.Interfaces.Repositories;

namespace Wimm.DAL.Repositories
{
    public class UserRepository:SqlLightBaseRepository,IUserRepository
    {
        public UserRepository(SQLiteAsyncConnection connection)
            :base(connection)
        {
            
        }

        #region SeedData
        public override async Task<bool> SeedData()
        {
            bool seedIsNeeded = await base.SeedData();

            if (seedIsNeeded)
            {
                //create daabase schema
                await _connection.CreateTableAsync<User>();

                //User user1 = new User("Admin","1234");

                //await _connection.InsertAsync(user1);
            }

            return seedIsNeeded;
        }
        #endregion

        public async Task<List<User>> LoadUsers()
        {
            return await _connection.Table<User>().ToListAsync();
        }

        public async Task<User> FindUserByLogin(string login)
        {
            return await _connection.Table<User>().Where(u => u.DisplayName.Equals(login)).FirstOrDefaultAsync();
        }

        public async Task<User> FindUserByPassword(string password)
        {
            return await _connection.Table<User>().Where(u => u.Password.Equals(password)).FirstOrDefaultAsync();
        }
        public async Task<User> FindUserByLoginAndPassword(string login, string password)
        {
            return await _connection.Table<User>().Where(u => u.DisplayName.Equals(login) && u.Password.Equals(password)).FirstOrDefaultAsync();
        }
        public async Task<User> LoadUser()
        {
            int userCount = await _connection.Table<User>().CountAsync();

            if (userCount == 1)
            {
                return await _connection.Table<User>().FirstOrDefaultAsync();
            }
            if (userCount > 1)
            {
                return await _connection.Table<User>().FirstAsync();
            }
            else
                return null;
        }

        public async Task<User> InsertUser(User newUser)
        {
           await _connection.InsertAsync(newUser);

            return newUser;
        }
    }
}
